package com.xjm.api.web;

import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xjm.constant.AppConst;
import com.xjm.entity.model.AddressesModel;
import com.xjm.entity.model.OrdersModel;
import com.xjm.entity.model.UsersModel;
import com.xjm.entity.vo.Result;
import com.xjm.service.IAddressesService;
import com.xjm.service.IOrdersService;
import com.xjm.service.UserService;
import com.xjm.utils.RedisUtil;
import com.xjm.utils.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    private final RedisUtil redisUtil;

    private final IOrdersService ordersService;

    private final IAddressesService addressesService;

    /**
     * 注册
     *
     * @param userModel 用户信息
     * @return 结果
     */
    @PostMapping("/register")
    public Result<Void> register(@RequestBody UsersModel userModel) {
        return userService.register(userModel);
    }

    /**
     * 登录
     */
    @PostMapping("/login")
    public Result<JSON> login(@RequestBody UsersModel userModel) {
        return userService.login(userModel);
    }

    @GetMapping("/logout")
    public Result<Void> logout(HttpServletRequest request) {
        String authorization = request.getHeader("Authorization");
        if (authorization != null) {
            String token = authorization.substring(7);
            redisUtil.delete(AppConst.USER_TOKEN_PREFIX + token);
        }
        return Result.success("退出成功");
    }

    //生成二维码
    @GetMapping("/getQr")
    public void getQr(@RequestParam String uuid, HttpServletResponse response) throws IOException {
        redisUtil.set(uuid, 0, 15);
        ClassPathResource classPathResource = new ClassPathResource("static/images/logo.png");
        QrCodeUtil.generate("/user/auth/" + uuid,
                QrConfig.create()
                        .setWidth(400)
                        .setHeight(400)
                        .setImg(classPathResource.getFile()),
                "png",
                response.getOutputStream());
    }

    //获取二维码状态
    @GetMapping("/getQrStatus")
    public Result<JSON> getQrStatus(@RequestParam String uuid) {
        return userService.getQrStatus(uuid);
    }

    // 认证中
    @PutMapping("auth/{uuid}/{token}")
    public Result<String> auth(@PathVariable String uuid, @PathVariable String token) {
        return userService.auth(uuid, token);
    }

    //确认登录
    @PutMapping("confirm/{uuid}")
    public Result<Void> confirm(@PathVariable String uuid) {
        return userService.confirm(uuid);
    }

    //取消登录
    @PutMapping("cancel/{uuid}")
    public Result<Void> cancel(@PathVariable String uuid) {
        return userService.cancel(uuid);
    }

    // 上传头像
    @PostMapping("/avatar")
    public Result<String> avatar(MultipartFile file) {
        if (file == null) return Result.error("上传失败");
        String path = userService.uploadAvatar(file);
        return Result.success("上传成功", path);
    }

    // 更新
    @PutMapping("/update")
    public Result<UsersModel> update(@RequestBody UsersModel usersModel) {
        usersModel.setId(UserContext.getUserId());
        userService.updateById(usersModel);
        return Result.success();
    }

    @GetMapping("/info")
    public Result<JSON> info() {
        UsersModel usersModel = userService.getById(UserContext.getUserId());
        usersModel.setPassword(null);
        JSONObject json = new JSONObject();
        json.putByPath("user", usersModel);
        // 统计
        json.putByPath("count.pending", ordersService.count(new LambdaQueryWrapper<OrdersModel>().eq(OrdersModel::getUserId, UserContext.getUserId()).eq(OrdersModel::getStatus, "pending")));
        json.putByPath("count.processing", ordersService.count(new LambdaQueryWrapper<OrdersModel>().eq(OrdersModel::getUserId, UserContext.getUserId()).eq(OrdersModel::getStatus, "processing")));
        json.putByPath("count.shipped", ordersService.count(new LambdaQueryWrapper<OrdersModel>().eq(OrdersModel::getUserId, UserContext.getUserId()).eq(OrdersModel::getStatus, "shipped")));
        json.putByPath("count.completed", ordersService.count(new LambdaQueryWrapper<OrdersModel>().eq(OrdersModel::getUserId, UserContext.getUserId()).eq(OrdersModel::getStatus, "completed")));
        json.putByPath("address", addressesService.getOne(new LambdaQueryWrapper<AddressesModel>()
                .eq(AddressesModel::getUserId, UserContext.getUserId())
                .eq(AddressesModel::getIsDefault, 1)));
        return Result.success(json);
    }
}
